package com.dongdongshop.sms;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.dongdongshop.constant.RedisRegisterConst;
import com.dongdongshop.util.SmsUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 发送验证码短信
 * @Author Eayon
 * @Date 2020/3/10 12:28
 */
@Component
@RocketMQMessageListener(topic = "sms-topic",consumerGroup = "sms-consumer")
public class SendSms implements RocketMQListener<String> {

    @Autowired
    private SmsUtil smsUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${aliyun.sms.template_code}")
    private String templateCode;

    @Value("${aliyun.sms.sign_name}")
    private String signName;

    private static final Logger log = LoggerFactory.getLogger(SendSms.class);

    /**
     * 发送验证码短信
     * @param phone  接收到的消息，也就是手机号
     */
    @Override
    public void onMessage(String phone) {
        //使用lang3字符串工具包生成一个4位数的随机数字当作验证码
        String code = RandomStringUtils.randomNumeric(4);
        //因为生产的验证码需要在其他服务再用户注册的时候进行验证码校验是否正确，所以我们放入redis，并设置30分钟有效期
        redisTemplate.boundValueOps(RedisRegisterConst.VERIFICATION_CODE + phone).set(code,30, TimeUnit.MINUTES);
        //发送的参数一定要是key-value结构  所以使用map封装一下
        Map<String,Object> map = new HashMap();
        //这里的key一定要和阿里云中短信模板中写的占位符保持一致，才能阿里云读取
        map.put("sms_code",code);
        //而且发送的参数一定是json格式，所以转换一下
        String param = JSONObject.toJSONString(map);
        //发送短信后返回的结果   OK代表发送成功
        String message = null;
        try {
            //按照短信模板和签名发送短信验证码并返回发送结果
            SendSmsResponse sendSmsResponse = smsUtil.sendSms(phone, templateCode, signName, param);
            message = sendSmsResponse.getMessage();
        } catch (ClientException e) {
            log.error("发送验证码异常",e);
        }
        log.info("发送短信结果："+message);
    }
}
